"""
设备基类
Base Device Class

提供所有IoT设备的基础实现
Provides base implementation for all IoT devices
"""

import logging
from typing import Dict, Any, Optional
from abc import abstractmethod
from datetime import datetime

from ..interfaces.device_interface import DeviceInterface

logger = logging.getLogger(__name__)


class BaseDevice(DeviceInterface):
    """
    设备基类
    Base Device Class
    
    提供IoT设备的基础功能实现
    Provides basic functionality implementation for IoT devices
    """
    
    def __init__(self, device_id: str):
        """
        初始化基础设备
        Initialize base device
        
        Args:
            device_id (str): 设备唯一标识符 / Device unique identifier
        """
        super().__init__(device_id)
        self.logger = logging.getLogger(f"{self.__class__.__name__}.{device_id}")
        self.metadata = {}
        self.last_data_timestamp = None
        
        self.logger.info(f"设备初始化: {device_id} / Device initialized: {device_id}")
    
    async def log_data_received(self, action: str, data: Dict[str, Any]) -> None:
        """
        记录接收到的数据
        Log received data
        
        Args:
            action (str): 操作类型 / Action type
            data (Dict[str, Any]): 数据内容 / Data content
        """
        self.last_data_timestamp = datetime.now()
        self.logger.info(f"收到 {action} 数据 / Received {action} data: {self.device_id}")
        
        # 更新在线状态 / Update online status
        await self.update_online_status(True)
    
    async def handle_error(self, error: Exception, context: str = "") -> None:
        """
        处理错误
        Handle error
        
        Args:
            error (Exception): 异常对象 / Exception object
            context (str): 错误上下文 / Error context
        """
        error_msg = f"设备错误 / Device error: {self.device_id}, 上下文 / Context: {context}, 错误 / Error: {str(error)}"
        self.logger.error(error_msg, exc_info=True)
        
        # 可以在这里添加错误上报逻辑
        # Error reporting logic can be added here
    
    def update_metadata(self, key: str, value: Any) -> None:
        """
        更新设备元数据
        Update device metadata
        
        Args:
            key (str): 元数据键 / Metadata key
            value (Any): 元数据值 / Metadata value
        """
        self.metadata[key] = value
        self.logger.debug(f"更新元数据 / Updated metadata: {key} = {value}")
    
    def get_metadata(self, key: str = None) -> Any:
        """
        获取设备元数据
        Get device metadata
        
        Args:
            key (str, optional): 元数据键 / Metadata key
            
        Returns:
            Any: 元数据值或全部元数据 / Metadata value or all metadata
        """
        if key is None:
            return self.metadata
        return self.metadata.get(key)
    
    async def health_check(self) -> Dict[str, Any]:
        """
        设备健康检查
        Device health check
        
        Returns:
            Dict[str, Any]: 健康状态信息 / Health status information
        """
        health_status = {
            'device_id': self.device_id,
            'device_type': self.device_type,
            'is_online': self.is_online,
            'last_heartbeat': self.last_heartbeat,
            'last_data_timestamp': self.last_data_timestamp,
            'metadata': self.metadata,
            'status': 'healthy' if self.is_online else 'offline'
        }
        
        # 检查最后心跳时间 / Check last heartbeat time
        if self.last_heartbeat:
            time_diff = (datetime.now() - self.last_heartbeat).total_seconds()
            if time_diff > 300:  # 5分钟无心跳视为异常 / 5 minutes without heartbeat is considered abnormal
                health_status['status'] = 'warning'
                health_status['warning'] = f"无心跳超过 {time_diff:.0f} 秒 / No heartbeat for {time_diff:.0f} seconds"
        
        return health_status
    
    @abstractmethod
    async def process_data(self, raw_data: Dict[str, Any]) -> Optional[Any]:
        """
        处理原始数据 - 子类必须实现
        Process raw data - must be implemented by subclasses
        """
        pass
    
    @abstractmethod
    async def validate_data(self, data: Dict[str, Any]) -> bool:
        """
        验证数据有效性 - 子类必须实现
        Validate data integrity - must be implemented by subclasses
        """
        pass
    
    @abstractmethod
    async def send_command(self, command: Dict[str, Any]) -> Dict[str, Any]:
        """
        发送命令 - 子类必须实现
        Send command - must be implemented by subclasses
        """
        pass